<template>
  <section class='f-register' :style="{'height': currentHeight + 'px'}">
    <section style="padding-top:25px;padding-left:29px">
      <img style="width:16px;height:16px" src="@/assets/icons/login_icon_close@2x.png" @click="goBakc">
      <p style="font-size: 20px;margin:40px 0">注册账号</p>
    </section>

    <van-form ref="ruleFormRef" @submit="onSubmit">
      <van-cell-group inset style="background-color: transparent;">
        <van-field v-model="form.shopName" clearable name="shopName" placeholder="请输入商户名称"
          :rules="[{ required: true, message: '请输入商户名称' }]" @blur="checkName">
          <template #left-icon>
            <img style="width:16px;height:15px;margin-top:3px" class="f-mr-10" src="@/assets/icons/login_icon_name@2x.png" alt="">
          </template>
        </van-field>
        <van-field v-model="form.shopUserPhone" clearable name="shopUserPhone" placeholder="请输入要注册的手机号码"
          :rules="[{ required: true, message: '请输入要注册的手机号码' }]">
          <template #left-icon>
            <img style="width:14px;height:17px;margin-top:3px" class="f-mr-10" src="@/assets/icons/login_icon_phone.png" alt="">
          </template>
          <template #extra>
            <div class="f-ml-10" style="font-size: 14px;color: #074DC4;" @click="getMsgCodeHandle">{{count? count + '秒': '获取验证码'}}
            </div>
          </template>
        </van-field>
        <van-field v-model="form.verificationCode" clearable name="verificationCode" placeholder="请输入验证码" maxlength="6"
          :rules="[{ required: true, message: '请输入验证码' }]">
          <template #left-icon>
            <img style="width:16px;height:18px;margin-top:3px" class="f-mr-10" src="@/assets/icons/login_icon_code@2x.png" alt="">
          </template>
        </van-field>
        <van-field v-model="form.firstPassword" :type="showPwd?'':'password'" clearable name="firstPassword" placeholder="请设置密码"
          style="border-bottom:1px solid red"
          :rules="[{ required: true, message: '请填写密码' },{ validator: validatorPasswordNew, message: resetPasswordMsg }]">>
          <template #left-icon>
            <van-icon v-show="!showPwd" name="closed-eye" style="width:16px" class="f-mr-10" @click="showPwd = true" />
            <van-icon v-show="showPwd" name="eye-o" style="width:16px" class="f-mr-10" @click="showPwd = false" />
          </template>
        </van-field>
        <van-field v-model="form.secondPassword" :type="showPwd?'':'password'" clearable name="secondPassword"
          placeholder="二次确认密码" style="border-bottom:1px solid red"
          :rules="[{ required: true, message: '请填写确认密码' },{ validator: validatorPasswordNew1, message: '两次密码不一致' }]">
          <template #left-icon>
            <p style="width:16px" class="f-mr-10"></p>
          </template>
        </van-field>
        <van-field v-model="form.email" clearable name="email" placeholder="请输入邮箱账号"
          :rules="[{ required: true, message: '请输入邮箱账号' }]">
          <template #left-icon>
            <img style="width:15px;height:15px;margin-top:3px" class="f-mr-10" src="@/assets/icons/login_icon_email.png" alt="">
          </template>
        </van-field>
        <van-field v-model="form.shopCode" clearable name="shopCode" placeholder="请输入邀请码"
          :rules="[{ required: true, message: '请输入邀请码' }]">
          <template #left-icon>
            <img style="width:15px;height:17px;margin-top:3px" class="f-mr-10" src="@/assets/icons/login_icon_invitecode@2x.png"
              alt="">
          </template>
        </van-field>
        <van-field v-show="false" />
      </van-cell-group>
      <div class="f-submit-btn">
        <van-button round block type="primary" color="#488BFE" native-type="submit">
          注册
        </van-button>
      </div>
    </van-form>

    <img class="f-img" src="@/assets/imgs/login_bg.png" alt="">

    <section class="f-bottom">
      <van-checkbox v-model="checked" checked-color="#488BFE" icon-size="15px">我已阅读并同意《用户使用协议》</van-checkbox>
    </section>
  </section>
</template>
<script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import { getStore, phoneFormat, successDeal, warningDeal } from '@/utils/utils';
import hexMD5 from "@/utils/md5.min.js"
import { showDialog } from 'vant';
import api from './api'

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref()

    const state = reactive({
      form: {
        "firstPassword": "",
        "secondPassword": "",
        "shopCode": "",
        "shopName": "",
        "shopUserPhone": "",
        "source": 1,
        "verificationCode": "",
        email: ""
      },
      showPwd: false,

      checked: false,

      counter: 0, // 计时器
      count: 0,
      currentHeight: '',
      passwordMsg: ''
    })

    onMounted(() => {
      state.currentHeight = window.innerHeight
      state.form.shopCode = route.query.shopCode
    })

    // 获取短信验证码
    const getMsgCodeHandle = () => {
      if (state.count) return
      ruleFormRef.value.validate(['shopUserPhone']).then(res => {
        state.count = 120;
        countDown();

        let json = {
          phone: state.form.shopUserPhone,
          source: 1,
          type: 1, // 1-注册，2-找回密码 3-修改手机号
        }
        api.getMsgCode(json).then((res) => {
          if (res) {
            successDeal('短信已发送！')
          }
        }).catch(err => {
          state.count = 0
          clearCounter()
        })
      })
    }

    //计时
    const countDown = () => {
      let count = state.count;

      clearCounter();
      state.counter = setInterval(() => {
        count--;
        state.count = count;
        if (count == 0) {
          clearCounter();
        }
      }, 1000);
    }

    //清除定时器
    const clearCounter = () => {
      clearInterval(state.counter);
    }

    const checkName = () => {
      let json = {
        shopName: state.form.shopName
      }
      api.checkName(json).then(res => { })
    }

    const onSubmit = () => {
      if (!state.checked) {
        warningDeal('请同意用户使用协议！')
        return
      }

      let json = JSON.parse(JSON.stringify(state.form))
      json.firstPassword = hexMD5(json.firstPassword)
      json.secondPassword = hexMD5(json.secondPassword)
      api.register(json).then(res => {
        successDeal('注册成功，请下载App！')
        setTimeout(() => {
          goBakc()
        }, 1000)
      })
    };

    const goBakc = () => {
      router.go(-1)
    }

    const resetPasswordMsg = (value, rule) => {
      return state.passwordMsg
    }

    const validatorPasswordNew = (val) =>
      new Promise((resolve) => {
        const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{8,30}$/;
        if (reg.test(val)) {
          resolve(true)
        } else {
          state.passwordMsg = '密码长度8位以上,由大写字母、小写字母、数字、特殊符号中三种方式组成'
          resolve(false)
        }
      });

    const validatorPasswordNew1 = (val) =>
      new Promise((resolve) => {
        if (state.form.firstPassword === val) {
          resolve(true)
        } else {
          resolve(false)
        }
      });

    return {
      ...toRefs(state),
      ruleFormRef,
      onSubmit,
      getMsgCodeHandle,
      goBakc,
      checkName,
      resetPasswordMsg,
      validatorPasswordNew,
      validatorPasswordNew1
    }
  }
}
</script>
<style lang='scss' scoped>
.f-register {
  position: relative;
  overflow: hidden;
  .f-submit-btn {
    margin-top: 70px;
    padding: 0 60px;
  }
  .f-bottom {
    position: absolute;
    bottom: 20px;
    left: 0px;
    width: 100%;
    display: flex;
    justify-content: center;
    font-size: 13px;
    color: #424242;
    .van-checkbox__icon--round .van-icon {
      border-color: #424242;
    }
    .van-checkbox__icon--checked .van-icon {
      border-color: var(--van-checkbox-checked-icon-color);
    }
  }
  .f-img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
  }
  .van-cell {
    background-color: transparent;
  }
}
</style>